#!/bin/sh

if [ -z "$1" ] || [ -z "$2" ]; then
	echo "Usage example: make_from_template.sh path/to/example_recipe_{{1a}}.json.template       list.tsv"
	echo "or:            make_from_template.sh path/to/example_from_{{1}}_to_{{2}}.json.template list1.txt list2.txt"
	exit 1
fi

if [ -z "$3" ]; then
	while read -r replace1a replace1b replace1c replace1d; do
		replace1="$replace1a"
		new_filename="$(printf '%s' "$1" | sed "s/{{1}}/$replace1/g; s/{{1a}}/$replace1a/g; s/{{1b}}/$replace1b/g; s/{{1c}}/$replace1c/g; s/{{1d}}/$replace1d/g; s/.template\$//")"
		echo "$new_filename"
		< "$1" sed "s/{{1}}/$replace1/g; s/{{1a}}/$replace1a/g; s/{{1b}}/$replace1b/g; s/{{1c}}/$replace1c/g; s/{{1d}}/$replace1d/g" > "$new_filename"
	done < "$2"
else
	while read -r replace1a replace1b; do
		replace1="$replace1a"
		while read -r replace2a replace2b; do
			replace2="$replace2a"
			new_filename="$(printf '%s' "$1" | sed "s/{{1}}/$replace1/g; s/{{1a}}/$replace1a/g; s/{{1b}}/$replace1b/g; s/{{2}}/$replace2/g; s/{{2a}}/$replace2a/g; s/{{2b}}/$replace2b/g; s/.template\$//")"
			echo "$new_filename"
			< "$1" sed "s/{{1}}/$replace1/g; s/{{1a}}/$replace1a/g; s/{{1b}}/$replace1b/g; s/{{2}}/$replace2/g; s/{{2a}}/$replace2a/g; s/{{2b}}/$replace2b/g; s/.template\$//" > "$new_filename"
		done < "$3"
	done < "$2"
fi
